import {
  reqAddOrUpdateCart,
  reqRemoveGood,
  reqShopCart,
  reqUpdateChecked,
} from "@/api";

const state = {
  goodsArr: [],
};
const mutations = {
  GETUSERCART(state, payload) {
    state.goodsArr = payload;
  },
};
const actions = {
  async getUserCart({ commit, state, dispatch, getters }) {
    let result = await reqShopCart();
    if (result.code == 200) {
      commit("GETUSERCART", result.data);
    }
  },
  async updateChecked(
    { commit, dispatch, state, getters },
    { skuId, isChecked }
  ) {
    let result = await reqUpdateChecked(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  async updateSkuNum({ commit, state, dispatch, getters }, { skuId, skuNum }) {
    let result = await reqAddOrUpdateCart(skuId, skuNum);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  async removeGood({ commit, state, dispatch, getters }, skuId) {
    let result = await reqRemoveGood(skuId);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  updateAllChecked({ commit, dispatch, state, getters }, isChecked) {
    // console.log(getters);
    let arr = [];
    getters.cartInfoList.forEach((good) => {
      if (good.isChecked != isChecked) {
        let ps = dispatch("updateChecked", { skuId: good.skuId, isChecked });
        arr.push(ps);
      }
    });
    return Promise.all(arr);
  },
  removeAllGood({ commit, dispatch, state, getters }) {
    let arr = [];
    getters.cartInfoList.forEach((list) => {
      if (list.isChecked == 1) {
        let pro = dispatch("removeGood", list.skuId);
        arr.push(pro);
      }
    });
    return Promise.all(arr);
  },
};
const getters = {
  cartInfoList(state) {
    return (state.goodsArr[0] || {}).cartInfoList || [];
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
